define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'sample_shipment_order/index' + location.search,
                    add_url: 'sample_shipment_order/add',
                    edit_url: 'sample_shipment_order/edit',
                    del_url: 'sample_shipment_order/del',
                    multi_url: 'sample_shipment_order/multi',
                    import_url: 'sample_shipment_order/import',
                    table: 'sample_shipment_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'customer_id', title: __('Customer_id')},
                        {field: 'inspection_report_id', title: __('Inspection_report_id')},
                        {field: 'order_id', title: __('Order_id')},
                        {field: 'salesperson', title: __('Salesperson'), operate: 'LIKE'},
                        {field: 'shipment_date', title: __('Shipment_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'is_tax_included', title: __('Is_tax_included')},
                        {field: 'currency', title: __('Currency'), operate: 'LIKE'},
                        {field: 'exchange_rate', title: __('Exchange_rate'), operate:'BETWEEN'},
                        {field: 'subtotal', title: __('Subtotal'), operate:'BETWEEN'},
                        {field: 'tax_amount', title: __('Tax_amount'), operate:'BETWEEN'},
                        {field: 'total_amount', title: __('Total_amount'), operate:'BETWEEN'},
                        {field: 'status', title: __('Status'), searchList: {"待发货":__('待发货'),"已发货":__('已发货'),"已签收":__('已签收'),"已取消":__('已取消')}, formatter: Table.api.formatter.status},
                        {field: 'created_at', title: __('Created_at')},
                        {field: 'updated_at', title: __('Updated_at')},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: function (value, row, index) {
                                // 使用默认的操作按钮格式化器
                                var defaultButtons = Table.api.formatter.operate.call(this, value, row, index);
                                // 添加自定义按钮
                                var customButton = [
                                    '<a class="excel-o" href="javascript:;" class="btn btn-success btn-xs btn-print" data-id="' + row.id + '" title="导出excel">',
                                    '<i class="fa fa fa-file-excel-o"></i>',
                                    '</a> '
                                ].join('');

                                return customButton + defaultButtons;
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
                        // 绑定自定义按钮事件
            table.on('post-body.bs.table', function () {
                // 打印按钮事件
                $(".excel-o").click(function () {
                    var id = $(this).data("id");
                    // 方法1：直接跳转到控制器方法
                    window.open('sample_shipment_order/export_excel?id=' + id);
                });
            });
        },
        add: function () {
            $(document).on("change", "#c-order_id", function(){
                var order_id = $(this).val();
                if (order_id) {
                    $.ajax({
                        url: 'sample_shipment_order/getCustomerDemandData',
                        type: 'post',
                        data: {order_ids: order_id},
                        dataType: 'json',
                        success: function(response) {
                            if (response.code === 1) {
                                var customerDemandTableBody = $("#customer-demand-table tbody");
                                customerDemandTableBody.empty(); // 清空现有数据
                                if (response.data.length > 0) {
                                    $("#customer-demand-table").show();
                                    $.each(response.data, function(i, item) {
                                        var row = '<tr>' +
                                            '<td>' + item.product_name + '</td>' +
                                            '<td>' + item.customer_name + '</td>' +
                                            '<td>' + item.product_id + '</td>' +
                                            '<td>' + item.customer_id + '</td>' +
                                            '<td><input type="number" class="form-control" name="customer_demand_quantity[' + item.id + ']" value="0"></td>' +
                                            '</tr>';
                                        customerDemandTableBody.append(row);
                                    });
                                } else {
                                    $("#customer-demand-table").hide();
                                }
                            } else {
                                console.error(response.msg);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求失败:', error);
                        }
                    });
                }


            });
            Controller.api.bindevent();
        },
        edit: function () {
            // 页面加载时检查c-customer_demand_json是否有值，如果有则解析并渲染到表格
            var load_flag = 1;
            var initial_customer_demand_json = $("#c-customer_demand_json").val();
            console.log(initial_customer_demand_json);
            if (initial_customer_demand_json) {
                load_flag = 1;
                try {
                    var customerDemandData = JSON.parse(initial_customer_demand_json);
                    var customerDemandTableBody = $("#customer-demand-table tbody");
                    customerDemandTableBody.empty(); // 清空现有数据
                    if (customerDemandData.length > 0) {
                        $("#customer-demand-table").show();
                        $.each(customerDemandData, function(i, item) {
                            var row = '<tr>' +
                                '<td>' + item.product_name + '</td>' +
                                '<td>' + item.customer_name + '</td>' +
                                '<td>' + item.product_id + '</td>' +
                                '<td>' + item.customer_id + '</td>' +
                                '<td><input type="number" class="form-control" name="customer_demand_quantity[' + item.product_id + '][' + item.customer_id + ']" value="' + item.quantity + '"></td>' +
                                '</tr>';
                            customerDemandTableBody.append(row);
                        });
                    } else {
                        $("#customer-demand-table").hide();
                    }
                } catch (e) {
                    console.error("解析客户需求JSON失败:", e);
                }
            }

            $(document).on("change", "#c-order_id", function(){
                var order_id = $(this).val();
                if (order_id) {
                    $.ajax({
                        url: 'sample_shipment_order/getCustomerDemandData',
                        type: 'post',
                        data: {order_ids: order_id},
                        dataType: 'json',
                        success: function(response) {
                            // debugger
                            if (load_flag != 3){
                                load_flag ++;
                                return;
                            }
                            if (response.code === 1 ) {
                                var customerDemandTableBody = $("#customer-demand-table tbody");
                                customerDemandTableBody.empty(); // 清空现有数据
                                if (response.data.length > 0) {
                                    $("#customer-demand-table").show();
                                    $.each(response.data, function(i, item) {
                                        var row = '<tr>' +
                                            '<td>' + item.product_name + '</td>' +
                                            '<td>' + item.customer_name + '</td>' +
                                            '<td>' + item.product_id + '</td>' +
                                            '<td>' + item.customer_id + '</td>' +
                                            '<td><input type="number" class="form-control" name="customer_demand_quantity[' + item.id + ']" value="0"></td>' +
                                            '</tr>';
                                        customerDemandTableBody.append(row);
                                    });
                                } else {
                                    $("#customer-demand-table").hide();
                                }
                            } else {
                                console.error(response.msg);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求失败:', error);
                        }
                    });
                }
            });
            // 页面加载时检查c-order_id是否有值，如果有则触发change事件
            var initial_order_id = $("#c-order_id").val();
            if (initial_order_id) {
                $("#c-order_id").trigger('change');
            }
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"),
                    // success callback
                    function(data, ret){
                        Fast.api.close(data);
                    },
                    // error callback
                    function(data, ret){
                        // Optional: handle error
                    },
                    // submit callback
                    function(data, ret) {
                        var customerDemandData = [];
                        $("#customer-demand-table tbody tr").each(function() {
                            var row = $(this);
                            var quantityInput = row.find('input[name^="customer_demand_quantity"]');
                            var quantity = quantityInput.val();
                            var productId = row.find('td:eq(2)').text(); // Assuming product_id is in the third column
                            var customerId = row.find('td:eq(3)').text(); // Assuming customer_id is in the fourth column
                            var productName = row.find('td:eq(0)').text(); // Assuming product_name is in the first column
                            var customerName = row.find('td:eq(1)').text(); // Assuming customer_name is in the second column

                            customerDemandData.push({
                                product_name: productName,
                                customer_name: customerName,
                                product_id: productId,
                                customer_id: customerId,
                                quantity: quantity
                            });
                        });
                        // 将收集到的数据设置到隐藏字段
                        $("input[name='row[customer_demand_json]']").val(JSON.stringify(customerDemandData));

                        return true; // 继续提交表单
                    },
                    // aftersubmit callback
                    function(data, ret){
                        // No specific action needed here based on the original comment.
                    }
                 );
            }
        }
    };
    return Controller;
});
